package com.lebang.medicalInquiry.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 数字人接口
 */
@Slf4j
public class DigitalMataHttpUtil {

   private static final   String requestUrl="http://szr.digitalmate.cn";
    /**
     * 创建项目: 问答库 直播都需要根据项目
     *
     * @return
     */
    public static String createDigitalProject(String projectName, Integer robotId, String voiceRobotId, String merchant_id, String sign,String backgroundImage,String bgmUrl,Integer bgmVolume) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {

            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/createproject?project_name=" + projectName +
                    "&robot_id=" + robotId + "&merchant_id=" + merchant_id + "&voice_robot_id=" + voiceRobotId + "&sign=" + sign+ "&background_image=" + backgroundImage+ "&bgm_url=" + bgmUrl+ "&bgm_volume=" + bgmVolume).post(RequestBody.create(MediaType.parse("text/plain")
                    , "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                String projectId = jsonObject.getJSONObject("data").getString("project_id");
                return projectId;
            } else {
                log.error("创建数字人项目错误:{}", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 修改项目: 问答库 直播都需要根据项目
     *
     * @return
     */
    public static boolean updateDigitalProject(String projectId, String merchant_id, Integer dhModelId, String voiceSpeed, String voiceVolume, Integer voiceRobotId,String backgroundImage,String bgmUrl,Integer bgmVolume) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        String url = requestUrl+"/updateproject?project_id=" + projectId +
                "&robot_id=" + dhModelId + "&merchant_id=" + merchant_id + "&voice_robot_id=" + voiceRobotId + "&voice_speed=" + voiceSpeed + "&voice_volume=" + voiceVolume+ "&background_image=" + backgroundImage+ "&bgm_url=" + bgmUrl+ "&bgm_volume=" + bgmVolume;
        try {

            Response execute = instance.newCall(new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("text/plain")
                    , "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code == 0) {
                return true;
            } else {
                log.error("项目属性修改错误错误:{},请求路劲:{}", result, url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 删除项目
     *
     * @return
     */
    public static String removeDigitalProject(String projectId, String merchant_id, String sign) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {
            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/deleteproject?project_id=" + projectId + "&merchant_id=" + merchant_id + "&sign=" + sign)
                    .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.error("删除数字人项目错误:{}", result);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除数字人项目错误:{}", result);
        }
        return null;
    }

    /**
     * 开播
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @param backgroundImage
     * @return json rtmpUrl:直播流  liveroomId:房间号
     */
    public static JSONObject startLive(String projectId, String merchant_id, String sign, String backgroundImage, Integer voiceType) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        String url = "";
        try {
            FormBody builder = new FormBody.Builder()
                    .add("background_image", backgroundImage)
                    .build();
            url = requestUrl+"/startlive?project_id=" + projectId + "&merchant_id=" + merchant_id + "&sign=" + sign + "&voice_type=" + voiceType;
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .post(builder).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            log.error("开播结果:{}", result);
            if (code != 0) {
                log.error("开播失败:{}", result);
            } else {
                final JSONObject data = jsonObject.getJSONObject("data");
                String rtmpUrl = data.getString("rtmp_url");
                String liveroomId = data.getString("liveroom_id");
                return data;
            }
        } catch (Exception e) {
            log.error("开播失败:{},请求路劲:{}", result, url);
            e.printStackTrace();

        }
        return null;
    }


    /**
     * 关播
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @return json
     */
    public static boolean closeLive(String projectId, String merchant_id, String sign, String liveroom_id) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        String url = "";
        try {

            url = requestUrl+"/closelive?project_id=" + projectId + "&liveroom_id=" + liveroom_id + "&merchant_id=" + merchant_id + "&sign=" + sign;
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            log.error("关播:{}", result);
            if (code != 0) {
                log.error("关播失败:{}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("关播失败:{},请求路劲:{}", result, url);
            e.printStackTrace();
        }
        return true;
    }


    /**
     * 上传多个问答对
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @return json
     */
    public static boolean batchUploadQaList(String projectId, String merchant_id, String sign, JSONArray jsonArray) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {
            final JSONObject json = new JSONObject();
            final JSONObject dataJson = new JSONObject();
            json.put("data", dataJson);
            dataJson.put("qa_list", jsonArray);
            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/uploadqalist?project_id=" + projectId + "&merchant_id=" + merchant_id + "&sign=" + sign)
                    .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toJSONString())).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            final JSONObject data = jsonObject.getJSONObject("data");
            if(data!=null){
                log.info("问答对结果：" + data.getInteger("success"));
            }

            if (code != 0) {
                log.error("上传多个问答对失败:{}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("上传多个问答对失败:{}", result);
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 更新一个问答对
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @return json
     */
    public static boolean updateQaList(String projectId, String merchant_id, String sign, String question, String answer, Integer qaId, Integer qa_type) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {

            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/updateqalist?project_id=" + projectId + "&merchant_id=" + merchant_id
                    + "&question=" + question + "&answer=" + answer + "&sign=" + sign + "&qa_id=" + qaId + "&qa_type=" + qa_type)
                    .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.error("更新一个问答对失败:{}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("更新一个问答对失败:{}", result);
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 删除问答对
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @return json
     */
    public static boolean deleteQaList(String projectId, String merchant_id, String sign, Integer qaId) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {

            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/deleteqalist?project_id=" + projectId + "&merchant_id=" + merchant_id
                    + "&sign=" + sign + "&qa_id=" + qaId)
                    .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.error("删除问答对失败:{}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("删除问答对失败:{}", result);
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 直播间弹幕
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     * @return json
     */
    public static boolean liveChat(String projectId, String merchant_id, String sign, String chatMsg, String liveroomId, String userId) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        try {

            Response execute = instance.newCall(new Request.Builder().url(requestUrl+"/chat?project_id=" + projectId + "&merchant_id=" + merchant_id
                    + "&chat_msg=" + chatMsg + "&sign=" + sign + "&liveroom_id=" + liveroomId + "&user_id=" + userId)
                    .post(RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "")).build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            log.error("直播间弹幕接口:{}", result);
            if (code != 0) {
                return false;
            }
        } catch (Exception e) {
            log.error("直播间弹幕失败:{}", result);
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 查询进度
     *
     * @param projectId
     * @param merchant_id
     * @param sign
     */
    public static Integer querySchedule(String projectId, String merchant_id, String sign) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        String url = "";
        try {

            url = requestUrl+"/queryschedule?project_id=" + projectId + "&merchant_id=" + merchant_id + "&sign=" + sign;
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .get().build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.error("查询进度:{}", result);

            } else {
                JSONObject data = jsonObject.getJSONObject("data");
                return data.getInteger("schedule");
            }
        } catch (Exception e) {
            log.error("查询进度:{},请求路劲:{}", result, url);
            e.printStackTrace();

        }
        return null;
    }

    public static void liveHearbeat(String projectId, String merchantId, String liveRoomId, String sign) {
        OkHttpClient instance = OkhttpClientUtils.getInstance();
        String result = "";
        String url = "";
        try {

            url = requestUrl+"/heartbeat?project_id=" + projectId + "&merchant_id=" + merchantId + "&sign=" + sign + "&liveroom_id=" + liveRoomId;
            Response execute = instance.newCall(new Request.Builder().url(url)
                    .get().build()).execute();
            ResponseBody body = execute.body();
            result = body.string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            final Integer code = jsonObject.getInteger("code");
            if (code != 0) {
                log.error("直播心跳:{}", result);
            }
        } catch (Exception e) {
            log.error("直播心跳:{}", result);
            e.printStackTrace();

        }
    }
}
